// 页面脚本

function dateStr() {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}年${month}月${day}日${hour}时${minute}分${second}秒`;
}

let sheetFormatData = []
// 生成excel并下载
function convertToExcel(data) {
  // 转换为工作簿对象
  var wb = XLSX.utils.book_new();
  var ws = XLSX.utils.aoa_to_sheet(data);
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 生成Excel文件的Blob对象
  var wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
  try {
    var blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    // 创建一个隐藏的a元素用于下载
    var elem = window.document.createElement('a');
    elem.href = window.URL.createObjectURL(blob);
    elem.download = `${dateStr()}--发货清单.xlsx`;
    document.body.appendChild(elem);
    elem.click(); // 触发下载
    document.body.removeChild(elem);
  } catch (e) {
    console.error(e, wbout);
  }
}

const theadArr = ['序号', '收件人', '手机号', "收货地址", "平台订单号", "商品信息", "规格信息", "商品数量", "备注"]
const updateDOM = (data) => {
  const tbodyDom = document.querySelector('.order-table tbody')
  data.forEach(row => {
    const tr = document.createElement('tr')
    row.forEach((item, index) => {
      const td = document.createElement('td')
      td.innerText = item
      td.title = item
      td.className = `col-${index + 1}`
      tr.appendChild(td)
    })
    tbodyDom.appendChild(tr)
  })
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action === 'update_table_dom') {
    const tempArr = request.orderArr.filter(item => {
      return sheetFormatData.findIndex(_item => item[4] === _item[4]) === -1
    })
    console.log("待更新DOM数据", tempArr);
    sheetFormatData = request.orderArr
    updateDOM(tempArr)
  }
  if (request.action === 'collection_completed') {
    alert("本页数据采集完毕")
  }
});


// 点击获取数据
document.querySelector('#exportBtn').addEventListener('click', async () => {
  // chrome.runtime.sendMessage({ action: 'export_table' });
  let [tab] = await chrome.tabs.query({
    active: true,
    currentWindow: true
  });
  // popup.js和content.js之间的通讯需要使用chrome.tabs
  chrome.tabs.sendMessage(tab.id, {
    action: 'getPageData',
    XLSX
  })
});

document.querySelector('#downloadBtn').addEventListener('click', () => {
  console.log(sheetFormatData);
  convertToExcel([theadArr,
    ...sheetFormatData])
});
